package com.nur.noteishon;

import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;

public class CustomDatePicker extends Button {

	private DatePicker picker;
	private Activity activityParent;

	private int year;
	private int month;
	private int day;

	private DatePickerDialog.OnDateSetListener datePickerListener;

	public CustomDatePicker(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public CustomDatePicker(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public CustomDatePicker(Context context) {
		super(context);
		init();
	}

	public Activity getActivityParent() {
		return activityParent;
	}

	public void setParent(Activity parent) {
		this.activityParent = parent;
	}

	private void init(){
		picker = new DatePicker(getContext());
		final Calendar c = Calendar.getInstance();
		year = c.get(Calendar.YEAR);
		month = c.get(Calendar.MONTH);
		day = c.get(Calendar.DAY_OF_MONTH);
 
		// set current date into textview
		setText(new StringBuilder()
			// Month is 0 based, just add 1
			.append(month + 1).append("-").append(day).append("-")
			.append(year).append(" "));
		
		datePickerListener = new DatePickerDialog.OnDateSetListener() {

				// when dialog box is closed, below method will be called.
				public void onDateSet(DatePicker view, int selectedYear,
						int selectedMonth, int selectedDay) {
					year = selectedYear;
					month = selectedMonth;
					day = selectedDay;

					// set selected date into textview
					setText(new StringBuilder().append(month + 1).append("-")
							.append(day).append("-").append(year).append(" "));

					// set selected date into datepicker also
					picker.init(year, month, day, null);

				}
			};
		
		picker.init(year, month, day, null);
		
		setOnClickListener(new OnClickListener() {
			 
			public void onClick(View v) {
				showDatePicker();
 
			}
 
		});
	}

	public void showDatePicker() {
		if(activityParent == null)
			return;
		
		DatePickerDialog d = new DatePickerDialog(getContext(), datePickerListener, 
                year, month,day);
		d.show();
 
	}
	
	public Date getSelectedDate(){
		Date date = new Date();
		date.setDate(picker.getDayOfMonth());
		date.setMonth(picker.getMonth());
		date.setYear(picker.getYear());
		return date;
	}

}
